﻿using Future.Common.Models;
using Future.IDAL;
using Future.Model.DtoModel;
using Future.Model.SysModel;
using System.Text;

namespace Future.DAL
{
    /// <summary>
    /// 描述：角色数据访问类
    /// 创建人： yangkai
    /// 创建时间：2022/12/5 16:40:36
    /// </summary>
    public class RoleDAL : BaseDAL<RoleModel>, IRoleDAL
    {
        public List<RoleModel> GetRolesByUserId(Guid userId)
        {
            string sql = @"select distinct Sys_Role.* 
                                from Sys_UserRole
                                join Sys_Role on Sys_UserRole.RoleId = Sys_Role.Id
                                where Sys_UserRole.UserId = @UserId";
            Dictionary<string, object> parameters = new()
            {
                { "UserId", userId }
            };
            return GetList(sql, parameters);
        }

        public PageModel<RoleModel> SelctPageList(RoleQueryDto roleQueryDto, PageParModel page)
        {
            string sql = @"SELECT [Id]
                                  ,[RoleName]
                                  ,[RoleCode]
                                  ,[OrderNum]
                                  ,[Status]
                                  ,[CreateBy]
                                  ,[CreateTime]
                                  ,[UpdateBy]
                                  ,[UpdateTime]
                                  ,[Remark]
                              FROM [Future].[dbo].[Sys_Role]
                              WHERE 1 = 1";

            StringBuilder stringBuilder = new();
            Dictionary<string, object> parameters = new();
            //这里可以利用反射和Attribute做个工具简化，不过不利于代码阅读，想偷懒的人可以去做
            if (!string.IsNullOrEmpty(roleQueryDto.RoleName))
            {
                stringBuilder.Append(" and RoleName like '%'+@RoleName+'%'");
                parameters.Add("RoleName", roleQueryDto.RoleName);
            }

            if (!string.IsNullOrEmpty(roleQueryDto.RoleCode))
            {
                stringBuilder.Append(" and RoleCode like '%'+@RoleCode+'%'");
                parameters.Add("RoleCode", roleQueryDto.RoleCode);
            }

            if (roleQueryDto.Status.HasValue)
            {
                stringBuilder.Append(" and Status = @Status");
                parameters.Add("Status", roleQueryDto.Status.Value);
            }

            if (roleQueryDto.StartTime.HasValue)
            {
                stringBuilder.Append(" and CreateTime > @StartTime");
                parameters.Add("StartTime", roleQueryDto.StartTime.Value);
            }

            if (roleQueryDto.EndTime.HasValue)
            {
                stringBuilder.Append(" and CreateTime <= @EndTime");
                parameters.Add("EndTime", roleQueryDto.EndTime.Value);
            }

            sql += stringBuilder.ToString();
            return PageList(sql, parameters, page, "OrderNum desc");
        }
    }
}
